import { defineStore } from 'pinia';
import { sendMessage, createChat, listMessages, listChats, saveMessage } from '@/api/chat';
import { v4 as uuidv4 } from 'uuid';

// 动态导入 Prism，避免重复声明
const initPrism = async () => {
  if (typeof window !== 'undefined' && !window.Prism) {
    const PrismModule = await import('prismjs');
    window.Prism = PrismModule.default;
  }
};

// 获取初始projectId的辅助函数
const getInitialProjectId = () => {
  if (typeof window === 'undefined') return 125;
  
  // 1. 从URL参数获取projectId
  const urlParams = new URLSearchParams(window.location.search);
  const urlProjectId = urlParams.get('projectId');
  if (urlProjectId && /^\d+$/.test(urlProjectId)) {
    console.log('[ChatStore] 从URL参数获取projectId:', urlProjectId);
    return parseInt(urlProjectId);
  }
  
  // 2. 从localStorage获取
  const storedProjectId = localStorage.getItem('currentProjectId');
  if (storedProjectId && /^\d+$/.test(storedProjectId)) {
    console.log('[ChatStore] 从localStorage获取projectId:', storedProjectId);
    return parseInt(storedProjectId);
  }
  
  console.log('[ChatStore] 使用默认projectId: 125');
  return 125;
};

export const useChatStore = defineStore('chat', {
  state: () => ({
    messages: [], // 当前会话的消息列表
    projectId: getInitialProjectId(),
    chatId: localStorage.getItem('currentChatId') || null, // 当前会话 ID
    chatList: [], // 会话列表
    isSending: false, // 消息发送状态
    uuid: '', // 用户唯一标识
    refreshCounter: 0, // 会话列表刷新计数器
    newlyCreatedChatId: null, // 新创建会话的ID
    broadcastChannel: null // BroadcastChannel实例
  }),
  actions: {
    uuidToNumber(uuid) {
      let number = 0;
      for (let i = 0; i < uuid.length && i < 6; i++) {
        const hexValue = uuid[i];
        let digit = 0;
        if (/[0-9a-fA-F]/.test(hexValue)) {
          digit = parseInt(hexValue, 16);
        }
        number = number * 16 + digit;
      }
      return number % 1000000;
    },

    // 初始化时检查UUID是否存在，如果没有则生成新的UUID
    initUUID() {
      let storedUUID = localStorage.getItem('user_uuid');
      if (!storedUUID) {
        storedUUID = uuidv4();
        localStorage.setItem('user_uuid', this.uuidToNumber(storedUUID));
      }
      this.uuid = storedUUID;
    },

    // 初始化BroadcastChannel监听
    initBroadcastChannel() {
      if (typeof window === 'undefined') return;
      
      try {
        // 移除旧的channel（如果存在）
        if (this.broadcastChannel) {
          this.broadcastChannel.close();
        }
        
        this.broadcastChannel = new BroadcastChannel('project_channel');
        console.log('[ChatStore] BroadcastChannel创建成功:', this.broadcastChannel);
        
        this.broadcastChannel.onmessage = (event) => {
          console.log('[ChatStore] 收到BroadcastChannel消息:', event.data, '来源:', event.origin);
          console.log('[ChatStore] 当前projectId:', this.projectId, '收到projectId:', event.data?.projectId);
          
          if (event.data && event.data.type === 'projectChanged' && event.data.projectId) {
            console.log('[ChatStore] 准备切换项目到:', event.data.projectId);
            this.switchProject(event.data.projectId);
          } else {
            console.log('[ChatStore] 消息格式不正确或缺少projectId');
          }
        };
        
        // 添加错误监听
        this.broadcastChannel.onmessageerror = (error) => {
          console.error('[ChatStore] BroadcastChannel消息错误:', error);
        };
        
        console.log('[ChatStore] BroadcastChannel初始化完成，监听: project_channel');
      } catch (error) {
        console.error('[ChatStore] BroadcastChannel初始化失败:', error);
      }
    },
    
    // 添加一个测试方法来验证BroadcastChannel是否工作
    testBroadcastChannel() {
      if (this.broadcastChannel) {
        const testMessage = {
          type: 'projectChanged',
          projectId: 999,
          timestamp: Date.now(),
          source: 'xiaogu-project'
        };
        this.broadcastChannel.postMessage(testMessage);
        console.log('[ChatStore] 测试消息已发送:', testMessage);
      }
    },

    // 切换项目
    async switchProject(newProjectId) {
      console.log('[ChatStore] 开始切换项目，从', this.projectId, '到', newProjectId);
      
      if (!newProjectId || newProjectId === this.projectId) {
        console.log('[ChatStore] 项目ID相同或无效，无需切换');
        return;
      }
      
      try {
        // 保存新的projectId到localStorage
        localStorage.setItem('currentProjectId', newProjectId.toString());
        
        // 更新projectId
        this.projectId = newProjectId;
        
        // 重置相关状态
        this.chatId = null;
        this.chatList = [];
        this.messages = [];
        localStorage.removeItem('currentChatId');
        
        console.log('[ChatStore] 项目切换完成，开始获取新项目的会话列表');
        
        // 重新获取会话列表
        await this.fetchChatList();
        
        console.log('[ChatStore] 新项目会话列表获取完成');
      } catch (error) {
        console.error('[ChatStore] 切换项目失败:', error);
      }
    },

    // 获取会话列表
    async fetchChatList() {
      console.log('[ChatStore] 开始获取会话列表，projectId:', this.projectId);
      try {
        const response = await listChats(this.projectId, this.uuid);
        console.log('[ChatStore] 获取会话列表成功，数量:', response.data.length);
        
        // 排序会话列表（按创建时间降序）
        const sortedChats = response.data.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
        this.chatList = sortedChats.map(item => {
          item.chatId = BigInt(item.chatId).toString();
          return item;
        });
        
        // 如果当前没有选中的会话，选择第一个会话
        if (!this.chatId && this.chatList.length > 0) {
          this.chatId = this.chatList[0].chatId;
          localStorage.setItem('currentChatId', this.chatId);
          console.log('[ChatStore] 自动选择第一个会话:', this.chatId);
        }
        
        // 增加刷新计数器触发视图更新
        this.refreshCounter++;
      } catch (error) {
        console.error('[ChatStore] 获取会话列表失败:', error);
      }
    },

    // 选择会话，切换当前会话
    async selectChat(chatId) {
      console.log('[ChatStore] 选择会话:', chatId);
      this.chatId = chatId;
      localStorage.setItem('currentChatId', chatId);
      await this.fetchMessages(chatId);
    },

    // 格式化消息
    formatMessage(message) {
      // 提取图片标签并保留
      const imgTagRegex = /<img[^>]+src="([^">]+)"[^>]*>/g;
      const imgTags = [];
      let formattedMessage = message.replace(imgTagRegex, (match, src) => {
        imgTags.push(match);
        return `__IMG_TAG_${imgTags.length - 1}__`;
      });
    
      // 处理代码块
      const codeBlockMatches = [];
      formattedMessage = formattedMessage.replace(/```(?:\s*(\w+))?\n([\s\S]*?)```/g, (match, language, codeContent) => {
        const lang = (language || 'plaintext').trim();
        codeBlockMatches.push({ codeContent, lang });
        return `__CODE_BLOCK_${codeBlockMatches.length - 1}__`;
      });
    
      // 处理换行
      formattedMessage = formattedMessage.replace(/\n/g, '<br>');
    
      // 恢复代码块
      codeBlockMatches.forEach((block, index) => {
        const codeBlockHTML = `
          <div class="code-block">
            <pre><code class="language-${block.lang}">${block.codeContent}</code></pre>
          </div>
        `;
        formattedMessage = formattedMessage.replace(`__CODE_BLOCK_${index}__`, codeBlockHTML);
      });
    
      // 恢复图片标签
      imgTags.forEach((imgTag, index) => {
        formattedMessage = formattedMessage.replace(`__IMG_TAG_${index}__`, imgTag);
      });
    
      return formattedMessage;
    },

    // 添加消息
    addMessage(message) {
      message.text = this.formatMessage(message.text);
      this.messages.push(message);
    },
    
    // 添加输出消息部分的方法
    async outputMessagePart(part, chatGptReply) {
      let buffer = '';
      for (const char of part) {
        buffer += char;
        chatGptReply.text = buffer + '_';
        this.messages = [...this.messages];
        await new Promise(resolve => setTimeout(resolve, 30));
        chatGptReply.text = buffer;
        this.messages = [...this.messages];
      }
    },

    // 发送消息到ChatGPT
    async sendMessageToChatGPT(userMessage) {
      console.log('[ChatStore] 发送消息到ChatGPT，projectId:', this.projectId);
      this.addMessage({ sender: 'user', text: userMessage.msg });
      this.addMessage({ sender: 'chatgpt', text: "努力思考中，请稍后" });
     
      this.isSending = true;
    
      try {
        const response = await sendMessage({
          projectId: this.projectId,
          language: 0,
          ...userMessage,
        });
        this.messages.splice(this.messages.length - 1, 1);
    
        const chatGptMessage = response.data;
        const formattedMessage = this.formatMessage(chatGptMessage);
        const chatGptReply = { sender: 'chatgpt', text: '', isTyping: true, isThinking: true };
        this.addMessage(chatGptReply);

        saveMessage({
          "chatId": this.chatId,
          "content": chatGptMessage
        });

        const codeRegex = /```(\w+)?\n([\s\S]*?)```/g;
        let lastIndex = 0;
        let match;

        while ((match = codeRegex.exec(formattedMessage)) !== null) {
          const [fullMatch, language, codeContent] = match;
          const nonCodeText = formattedMessage.slice(lastIndex, match.index);
          if (nonCodeText) {
            await this.outputMessagePart(nonCodeText, chatGptReply);
          }

          chatGptReply.text += `<pre><code class="language-${language || 'plaintext'}">`;
          this.messages = [...this.messages];
          await this.outputMessagePart(codeContent, chatGptReply);
          chatGptReply.text += `</code></pre>`;
          this.messages = [...this.messages];

          lastIndex = codeRegex.lastIndex;
        }

        if (lastIndex < formattedMessage.length) {
          const remainingText = formattedMessage.slice(lastIndex);
          await this.outputMessagePart(remainingText, chatGptReply);
        }

        setTimeout(async () => {
          await initPrism();
          if (window.Prism) {
            window.Prism.highlightAll();
          }
        }, 0);

        chatGptReply.isThinking = false;
        chatGptReply.isTyping = false;
        this.isSending = false;
        this.messages = [...this.messages];

        return chatGptMessage;
      } catch (error) {
        console.error('[ChatStore] 发送消息失败:', error);
        const errorMessage = '抱歉，我现在无法响应。';
        this.addMessage({ sender: 'chatgpt', text: errorMessage, isTyping: false });
        this.isSending = false;
        return errorMessage;
      }
    },

    // 创建新会话
    async createNewChat() {
      console.log('[ChatStore] 创建新会话，projectId:', this.projectId);
      try {
        const title = '新会话' + Math.random().toString(36).substring(2, 7);
        const response = await createChat({
          userId: this.uuid,
          projectId: this.projectId,
          title: title,
        });
        
        // 修复BigInt处理：确保response.data存在且有效
        const responseData = response?.data;
        if (!responseData) {
          console.error('[ChatStore] 创建新会话失败: response.data为空');
          return null;
        }
        
        const newChatId = typeof responseData === 'bigint' 
          ? responseData.toString() 
          : BigInt(responseData).toString();
        
        this.newlyCreatedChatId = newChatId;
        this.chatId = newChatId;
        localStorage.setItem('currentChatId', newChatId);
        
        // 清空当前会话消息
        this.messages = [];
        
        // 立即添加到会话列表开头
        this.chatList.unshift({
          chatId: newChatId,
          title: title,
          createTime: new Date().toISOString()
        });
        
        // 增加刷新计数器触发视图更新
        this.refreshCounter++;
        
        console.log('[ChatStore] 创建新会话成功:', newChatId);
        return newChatId;
      } catch (error) {
        console.error('[ChatStore] 创建新会话失败:', error);
        return null;
      }
    },

    // 获取指定会话的消息
    async fetchMessages(chatId) {
      console.log('[ChatStore] 获取会话消息:', chatId);
      try {
        await listMessages(chatId).then(response => {
          this.messages = response.data.map(msg => ({
            ...msg,
            text: this.formatMessage(msg.content),
            sender: msg.type === 0 ? 'user' : 'chatgpt'
          }));
          console.log('[ChatStore] 获取会话消息成功，数量:', this.messages.length);
        });
      } catch (error) {
        console.error('[ChatStore] 获取会话消息失败:', error);
      }
    },

    // 初始化方法
    async init() {
      console.log('[ChatStore] 初始化ChatStore');
      this.initUUID();
      this.initBroadcastChannel();
      await this.fetchChatList();
    }
  },
});